import { Col, Form, Modal, Row, Table, Space, Button, Select, DatePicker, Image } from 'antd';
import { memo, useEffect, useState } from "react"
import type { DealRecord } from "../services"
import { DealRecordInfoType, DealRecordStatus, QueryDealRecordListParams, queryDealRecordList } from "../services"
import { useRequest } from "ahooks"
import { ColumnsType } from "antd/es/table"
import dayjs from "dayjs"
import { Access } from '@umijs/max'
import { PAGINATION_CONFIG } from "@/constants"
import { enum2options } from "@/utils/enum2options"
import { jump2target } from '@/utils/common';

export interface DealRecordModalProps {
  open: boolean
  onCancel?: () => void
  userId?: string
}

export const DealRecordTable: React.FC<{userId?: string}> = props => {
  const [searchForm] = Form.useForm<QueryDealRecordListParams>()
  const [searchParams, setSearchParams] = useState<QueryDealRecordListParams>({
    pageNum: 1, pageSize: 10,
    beginTime: dayjs().subtract(31, 'days').format('YYYY-MM-DD 00:00:00'),
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  })
  const dealRecordList = useRequest(() => queryDealRecordList(searchParams), {
    ready: !!searchParams.userId,
    refreshDeps: [searchParams],
  })

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      infoType: formValues.infoType,
      beginTime: formValues.timeRange?.length ? formValues.timeRange[0].format('YYYY-MM-DD HH:mm:ss') : undefined,
      endTime: formValues.timeRange?.length ? formValues.timeRange[1].format('YYYY-MM-DD HH:mm:ss') : undefined,
      pageNum: 1,
    })
  }

  const openEditPage = (record: { id: string | undefined }) => {
    jump2target(`/normal/normalList/components/edit?type=add&from=1&id=${record.id}`, {
      needRefresh: true,
    });
    sessionStorage.setItem(
      '__/normal/normalList/components/edit_title',
      '手动退款',
    );
  };

  const columns: ColumnsType<DealRecord> = [
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      width: 120,
    },
    {
      title: '用户手机号',
      dataIndex: 'telephone',
      width: 140,
    },
    {
      title: '交易类型',
      dataIndex: 'infoType',
      width: 120,
      render: (val, record) => {
        return <Space>
          <span>{val && DealRecordInfoType[val]}</span>
          <Access accessible={val === DealRecordInfoType.退款}>
            <span>{DealRecordStatus[record.status]}</span>
          </Access>
        </Space>
      }
    },
    {
      title: '交易金额(元)',
      dataIndex: 'totalM',
      width: 120,
      render: (val, record) => {
        const { totalM, successMoney } = record
        if (!successMoney) return `${totalM}`
        else {
          if (successMoney !== totalM)
          {
            return `${totalM}/部分退款：${successMoney}`
          } else {
            return `${totalM}`
          }
        }
      }
    },
    {
      title: '图片',
      dataIndex: 'other',
      width: 100,
      render: val => val && <Image style={{height: 60}} src={val} />
    },
    {
      title: '交易时间',
      dataIndex: 'createTime',
      width: 160,
      render: createTime => dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')
    }
  ]

  useEffect(() => {
    if (props.userId) {
      searchForm.resetFields()
      setSearchParams({
        pageNum: 1, pageSize: 10, userId: props.userId
      })
    }
  }, [props.userId])

  return (
    <>
      <Form name='searchDealRecordForm' form={searchForm} onFinish={onFinish} layout="inline" initialValues={{timeRange: [dayjs().subtract(31, 'day'), dayjs()]}}>
        <Row gutter={[0, 16]} style={{width: '100%'}}>
          <Col span={6}>
            <Form.Item label='交易类型' name='infoType'>
              <Select placeholder='请选择' options={enum2options(DealRecordInfoType)} allowClear />
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item label='交易时间' name='timeRange'>
              <DatePicker.RangePicker showTime style={{width: '100%'}} disabledDate={current => current.isAfter(dayjs(), 'day')} />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Space>
              <Button type='primary' htmlType='submit' loading={dealRecordList.loading}>筛选</Button>
              <Button onClick={() => openEditPage({id:props.userId})}>手动退款</Button>
              <Button htmlType='reset'>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>
      <br />
      <Table<DealRecord>
        rowKey='id'
        loading={dealRecordList.loading}
        dataSource={dealRecordList.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: dealRecordList.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
    </>
  )
}

const DealRecordModal: React.FC<DealRecordModalProps> = props => {
  const onCancel = () => {
    props.onCancel?.()
  }

  return (
    <Modal
      title='交易记录列表'
      open={props.open}
      width={1200}
      onCancel={onCancel}
      footer={false}
    >
      <DealRecordTable
        userId={props.userId}
      />
    </Modal>
  )
}

export default memo(DealRecordModal)